#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time   : 2021/7/12 20:36
# @Author : cjw
from sqlalchemy.orm import Session
from coronavirus import models, schemas


def get_city(db: Session, city_id: int):
	"""
	根据城市id获取城市数据
	:param db: 数据库连接
	:param city_id: 城市id
	:return:
	"""
	return db.query(models.City).filter(models.City.id == city_id).first()


def get_city_by_name(db: Session, name: str):
	"""
	根据城市名称获取城市数据
	:param db: 数据库连接
	:param name: 城市名称
	:return:
	"""
	return db.query(models.City).filter(models.City.province == name).first()


def get_cities(db: Session, skip: int = 0, limit: int = 10):
	"""
	获取多个城市信息
	:param db: 数据库连接
	:param skip: 起始位置
	:param limit: 获取数量
	:return:
	"""
	return db.query(models.City).offset(skip).limit(limit).all()


def create_city(db: Session, city: schemas.CreateCity):
	"""
	创建城市
	:param db: 数据库连接
	:param city: 创建的城市信息
	:return:
	"""
	db_city = models.City(**city.dict())
	try:
		db.add(db_city)
		db.commit()
		db.refresh(db_city)
	except Exception:
		db.rollback()
	return db_city


def get_data(db: Session, city: str = None, skip: int = 0, limit: int = 10):
	"""
	获取城市疫情数据
	:param db: 数据库连接
	:param city: 城市名称
	:param skip: 起始位置
	:param limit: 获取数量
	:return:
	"""
	if city:
		# 外键关联查询，这里不是像Django ORM那样Data.city.province
		return db.query(models.Data).filter(models.Data.city.has(province=city)).all()
	return db.query(models.Data).offset(skip).limit(limit).all()


def create_city_data(db: Session, data: schemas.CreateData, city_id: int):
	"""
	创建城市疫情数据
	:param db: 数据库连接
	:param data: 疫情数据
	:param city_id: 城市id
	:return:
	"""
	db_data = models.Data(**data.dict(), city_id=city_id)
	try:
		db.add(db_data)
		db.commit()
		db.refresh(db_data)
	except Exception:
		db.rollback()
	return db_data